package auctionhaus

import com.auctionhaus.Listing
import com.auctionhaus.Customer
import com.auctionhaus.Bid
import grails.converters.*
import java.text.SimpleDateFormat
import org.springframework.mail.SimpleMailMessage.*
//import com.icegreen.greenmail.util.GreenMail
import org.springframework.mail.MailMessage.*

class ListingService {
    static expose=['xfire','jms']
    static transactional = true
    static destination = "queue.listing.listener"

    def mailService
    //def jmsService
    def companyEmailAddress = "ganzhullauctionhaus@gmail.com"
    def genericSubject = "Congratulations, from GanzHull Auction Haus!"

    def onMessage(xmlMessage){

	def listing = new XmlSlurper().parseText(xmlMessage)
	def seller = Customer.findById(listing.seller.@id.text())
        def endDate = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse(listing.endDateTime.text())
        def xmlListing = createListing(seller.emailAddress, seller.password, listing.listName.text(), endDate, listing.startBidPrice.text().toDouble(), listing.description?.text())
        println xmlListing as XML
    }

    def createListing(String sellerEmailAddress, String sellerPassword, String listName, Date endDate, Double startPrice, String description) {
        def listing = null
        def seller = Customer.findByEmailAddressIlike(sellerEmailAddress)
        if (seller && seller.password == sellerPassword) {
           listing = Listing.findByListNameAndSeller(listName,seller)
           if (!listing){
               listing = new Listing(creationDate:new Date(),
                                    listName:listName,
                                    endDateTime:endDate,
                                    startBidPrice:startPrice,
                                    seller:seller,
                                    description: description).save()
           }
        }
        return listing
    }

    def doListingExpired() {
        def listings = Listing.getAll()

        def now = new Date()
        listings.each{Listing l ->
            if (l.endDateTime < now && !l.isExpired()) {
                def listingToUpdate = Listing.findById(l.id)
                if (listingToUpdate) {
	                if (l.getMaxBid())
	                    listingToUpdate.setWinner(l.getMaxBid().buyer)
	                else
	                    listingToUpdate.setWinner(l.seller)

                    listingToUpdate.setExpired(true)
	                listingToUpdate.setWinningBid(l.getMaxBidPrice())
                    //jmsService.send(queue: "queue.notification", xmlMessage.toString(), "standard", null)

					boolean canEmail = false
					if (listingToUpdate.save(flush:true)){
						println 'Save Successful'
						canEmail = true
					}
					else
						println 'Save Failed.'  + listingToUpdate.errors

					def message = "Listing Expired: " + listingToUpdate.seller.loginName + "'s " + listingToUpdate.listName + ".  Sold to " + listingToUpdate.winner.loginName + " for " + listingToUpdate.getWinningBid()
					def xmlMessage = listingToUpdate as XML
					sendJMSMessage("queue.notification", message)
					sendJMSMessage("queue.notification", xmlMessage.toString())

			        if(canEmail){
						 def bidInstance = new Bid()
						 bidInstance = Listing.findByListName(l.listName)
						 def listingInstance = new Listing()
						 listingInstance = l

						 try{
								mailService.sendMail {
									to  listingToUpdate.seller.loginName, listingToUpdate.winner.loginName
									from companyEmailAddress
									subject genericSubject
									body( view:"/listing/completedListingEmail", model:[listingInstance:listingInstance, bidInstance:bidInstance])
								}	                
								
								println "Confirmation email sent to Seller: ${listingToUpdate.seller.loginName} and Winner ${listingToUpdate.winner.loginName}."

						
						}catch(Exception e) {
							println "Problem sending email ${e.message}"
						}
					}	                  
				}
            }
        }
    }
}
